from flask import Flask, flash, jsonify, Response, render_template, request, session, redirect, url_for
import simplejson as json
from flask_session import Session
import hashlib
from apps.admin import app, db
from apps.admin.models.admin import Admin
from apps.admin.util import common


@app.route("/login", methods=["GET", "POST"])
def login():
    if session.get('isLogin') == 1:
        flash('You were successfully logged in')
        return render_template("index.html")

    if request.method == 'GET':
        return render_template("login/login2.html")

    # if request.method == 'POST':
    username = request.form.get("username", type=str, default='')  # 获取表单数据
    password = request.form.get("password", type=str, default='')  # 获取表单数据
    captcha = request.form.get("captcha", type=str, default='')  # 获取表单数据
    values = request.values.get("username", type=str)  # 获取所有参数

    if username is None:
        result = {'code': 0, "msg": "用户不能为空"}
        return Response(json.dumps(result), mimetype='application/json')

    if password is None:
        result = {'code': 0, "msg": "密码不能为空"}
        return Response(json.dumps(result), mimetype='application/json')

    # 检查用户输入的验证码是否与session中的一致
    if captcha.upper() != session.get('captcha', '').upper():
        result = {'code': 0, 'msg': '验证码错误'}
        return Response(json.dumps(result), mimetype='application/json')

    info = Admin.query.filter_by(username=username).first()
    if info is None:
        result = {'code': 0, "msg": "用户不存在"}
        return Response(json.dumps(result), mimetype='application/json')
    # hash_object = hashlib.md5(password.encode())  # 将字符串编码并进行 MD5 加密
    # password = hash_object.hexdigest()  # 获取加密后的十六进制字符串
    print(info)
    password_en = common.encrypt_password(password+info.salt)
    print("密码；原始：%s；加密：%s" % (password, password_en))

    if info.status != 'normal':
        result = {'code': 0, "msg": "用户被锁定"}
    elif password_en == info.password:
        session['isLogin'] = 1
        session['username'] = username
        result = {'code': 1, "msg": "登录成功"}
    else:
        result = {'code': 0, "msg": "密码错误"}

    return Response(json.dumps(result), mimetype='application/json')


# 退出
@app.route("/logout", methods=["GET", "POST"])
def logout():
    if session.get('isLogin') is not None:
        del session['isLogin']
        # session.pop("isLogin", None)
    if session.get('username') is not None:
        del session['username']

    result = {'code': 200, "msg": "退出成功"}
    return Response(json.dumps(result), mimetype='application/json')
    # return redirect(url_for('login'))
